package com.abhishekduhoon.tfis;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PWMSingleScan extends HttpServlet {
	
	String transcriptionFactorName;
	String transcriptionFactorId;
	int transcriptionFactorLength;
    private static final long serialVersionUID = 1L;
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
                
        String userSequence = request.getParameter("userSequence");
        String transcriptionFactor = request.getParameter("transcriptionFactor");
        String error = "error.jsp";
    	
    	if(userSequence.isEmpty() || transcriptionFactor.isEmpty()){
    		response.sendRedirect(error);
    	}
    	
    	else{
        
    	String percent = request.getParameter("percent");
        int percentScore = Integer.parseInt(percent);
        userSequence = Methods.reformSequence(userSequence);
        String userSequenceCopy = userSequence;
        String line;
        String colorCodeStart = "<font color='red'>";
        String colorCodeEnd = "</font>";
        double[][] positionFrequencyMatrix;
        double[][] positionWeightMatrix;
    	int userSequenceLength = userSequence.length();
        double threshold;
    	int totalDetection = 0;
    	int index;
        int indexCopy;
        int check = 0;
        double score;
        int position;
        char base;
        
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<meta charset='UTF-8'>");
            out.println("<title>TFIS v1.0</title>");
            out.println("<meta name='description' content='Transcription Factor Information System'>");
            out.println("<meta name='keywords' content='TFIS, TF, TFBS'>");
            out.println("<link href='css/style.css' rel='stylesheet' type='text/css'>");
            out.println("</head>");
            out.println("<body>");
            out.println("<div id='wrapper'>");
            out.println("<div id='header'>");
            out.println("<div class='top_banner'>");
            out.println("<h1>TFIS v1.0</h1>");
            out.println("<p>Transcription Factor Information System</p>");
            out.println("</div>");
            out.println("</div>");
            out.println("<div id='page_content'>");
            out.println("<div class='navigation'>");
            out.println("<ul>");
            out.println("<li><a href='index.jsp'>Home</a></li>");
            out.println("<li><a href='about.jsp'>About</a></li>");
            out.println("<li><a href='doc.jsp'>Documentation</a></li>");
            out.println("<li><a href='feedback.jsp'>Feedback</a></li>");
            out.println("<li><a href='support.jsp'>Support</a></li>");
            out.println("</ul>");
            out.println("</div>");
            out.println("<div class='main_section'>");
            out.println("<h2>TFIS v1.0 : Result</h2>");
            out.println("<hr>");
            out.println("<div class='common_content'>");
            out.println("<h2>Positions Of Detected Transcription Factor Binding Sites (TFBSs) Are : ");
            out.println("<br>");
            
            try (BufferedReader br = new BufferedReader(new FileReader("pfm/pfm_all.txt"))){
                
            	while ((line = br.readLine()) != null) {
            		if(line.contains(transcriptionFactor)){
                        check = 1;
                        String delimiters = "[> ]";
                        String[] lineParts = line.split(delimiters);
                        transcriptionFactorId = lineParts[1];
                        transcriptionFactorName = lineParts[2];
                        line = br.readLine();
                        String A[] = line.split("\\s+");
                        transcriptionFactorLength = A.length;
                        positionFrequencyMatrix = new double[4][transcriptionFactorLength];
                        for(int i = 0; i < transcriptionFactorLength; i++){
                            positionFrequencyMatrix[0][i] = Double.parseDouble(A[i]); 
                        }
                        for(int i = 1; i < 4; i++){
                            line = br.readLine(); 
                            String CTG[] = line.split("\\s+");
                            for(int j = 0; j < transcriptionFactorLength; j++){
                                positionFrequencyMatrix[i][j] = Double.parseDouble(CTG[j]);
                            }
                        }
                             
                        positionWeightMatrix = Methods.pfmConversion(positionFrequencyMatrix,transcriptionFactorLength);
                        threshold = Methods.thresholdCalculator(positionWeightMatrix, transcriptionFactorLength, percentScore);
                        for(int i = 0; i <= userSequenceLength - transcriptionFactorLength; i++){
                        	score=0;
                        	position=0;
                        	for(int j = i; j < i + transcriptionFactorLength; j++){
                        		base = userSequence.charAt(j);
                        		if(base == 'A'){
                        			score = score + positionWeightMatrix[0][position];
                        		}
                        		else{
                        			if(base == 'C'){
                        				score = score + positionWeightMatrix[1][position];
                        			}
                        			else{
                        				if(base == 'G'){
                        					score = score + positionWeightMatrix[2][position];
                        				}
                        				else{
                        					score = score + positionWeightMatrix[3][position];
                        				}
                        			}
                        		}
                        		position++;
                        	}
                        	if(score >= threshold){
                        		index = i;
                        		indexCopy = index + totalDetection * 25;
                        		userSequenceCopy = Methods.insertCode(userSequenceCopy, colorCodeStart, indexCopy);
                        		indexCopy = indexCopy + transcriptionFactorLength + 18;
                        		userSequenceCopy = Methods.insertCode(userSequenceCopy, colorCodeEnd, indexCopy);
                        		index++;
                        		totalDetection++;
                        		out.println("<h2>" + totalDetection + " -> " + index + "</h2>");
                        		i = i + transcriptionFactorLength - 1;
                        	}
                        }
             		}
                    if(check==1){
                        break;
                    }
            	}
            }

            out.println("<h2>Total Transcription Factor Binding Sites (TFBSs) Detected : " + totalDetection + "</h2>");
            out.println("<hr>");
            out.println("<h2>Transcription Factor (TF) Name : "+transcriptionFactorName);
            out.println("<h2>Transcription Factor (TF) ID : " + transcriptionFactorId + "</h2>");
            out.println("<h2>Transcription Factor (TF) Links : <a href='http://www.ncbi.nlm.nih.gov/protein/?term="+transcriptionFactorName+"' target='_blank'>NCBI</a> & <a href='http://www.uniprot.org/uniprot/?query="+transcriptionFactorName+"&sort=score' target='_blank'>UNIPROT</a></h2>");
            out.println("<h2>Transcription Factor (TF) Length : " + transcriptionFactorLength + "</h2>");
            out.println("<h2>Sequence Length : " + userSequenceLength + "</h2>");
            out.println("<hr>");
            out.println("<h2>FASTA Format :</h2>");
            out.println("<span><h3>"+userSequenceCopy+"</h3></span>");
            out.println("</div>");
            out.println("</div>");
            out.println("<div class='clear'></div>");
            out.println("<div id='footer'>Sengupta <i>et al.</i> | Developed and Maintained by <a href='http://www.abhishekduhoon.com' target='_blank'>Abhishek Kumar</a>.");
            out.println("</div>");
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
           
        }
    	}
    }
}
    


            
        
    

    
    

    
    
    

